package com.jy.modules.cims.quota.service;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.CimsIrtUrlConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.component.deal.ICDeal;
import com.jy.modules.cims.component.quota.ICQuota;
import com.jy.modules.cims.component.sysAssist.BatchService;
import com.jy.modules.cims.data.common.dao.TCMmCooperorgDao;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaLoanDetailDTO;
import com.jy.modules.cims.data.dao.QuotaDao;
import com.jy.modules.cims.data.dao.QuotaLoanDetailDao;
import com.jy.modules.cims.data.dto.QuotaApplyParamDto;
import com.jy.modules.cims.data.dto.QuotaApplyResultDto;
import com.jy.modules.cims.data.dto.QuotaCreditDetailDto;
import com.jy.modules.cims.data.dto.QuotaDetailUnlockParamDto;
import com.jy.modules.cims.data.dto.QuotaDetailUnlockResultDto;
import com.jy.modules.cims.data.dto.QuotaDto;
import com.jy.modules.cims.data.dto.QuotaQueryDto;
import com.jy.modules.cims.data.interact.core.loan.response.LoanInfo;
import com.jy.modules.cims.interact.CIRCreditPoolIFImpl;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.interact.InteractClassInvokeService;
import com.jy.platform.core.common.BaseDTO;

/**
 * 额度处理服务
 */
@Service("com.jy.modules.cims.quota.service.QuotaService")
public class QuotaService {
	private static final Logger logger = LoggerFactory.getLogger(QuotaService.class);

    /**
     * 
     */
    public QuotaService() {
    }

    @Autowired
    private QuotaDao dao;

    @Autowired
    private QuotaLoanDetailDao quotaLoanDetailDao;

    @Autowired
    TCMmCooperorgDao tcmmCooperorgDao;

    @Autowired
    @Qualifier("com.jy.modules.cims.interact.InteractClassInvokeService")
    private InteractClassInvokeService interactClassInvokeService;

    @Autowired
    @Qualifier("com.jy.modules.cims.component.deal.CDealImpl")
    public ICDeal iCDeal;

    /**
     * 系统交互处理服务层
     */
    @Autowired
    @Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
    public ICInteract iCInteract;

    /**
     * 额度处理服务层
     */
    @Autowired
    @Qualifier("com.jy.modules.cims.component.quota.CQuotaImpl")
    public ICQuota iCQuota;

    @Autowired
    @Qualifier("com.jy.modules.cims.interact.CIRCreditPoolIFImpl")
    private CIRCreditPoolIFImpl creditPoolIFImpl;
    /**
     * 系统交互处理服务层
     */
    @Autowired
    @Qualifier("com.jy.modules.cims.interact.CInteractAssist")
    public IInteractAssist iInteractAssist;
    
    @Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.BatchService")
	public BatchService batchService;

    /**
     * 额度查询列表
     * 
     * @param dto
     * @return
     */
    public List<QuotaDto> getQuotaList(QuotaQueryDto dto) throws Exception {
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("dto", dto);
        List<QuotaDto> list = dao.searchQuota(searchParams);
        return list;
    }

    /**
     * 额度明细查询列表
     * 
     * @param dto
     * @return
     */
    public List<Object> getQuotaDetailList(QuotaQueryDto dto) throws Exception {
        // TODO implement here
        return null;
    }

    /**
     * 额度贷款明细查询列表
     * 
     * @param dto
     * @return
     */
    public List<TCMmQuotaLoanDetailDTO> getQuotaLoanDetailList(Map<String, Object> searchParams) throws Exception {

        return null;
    }

    /**
     * 获得额度申请流水号
     * 
     * @param quotaCode
     * @return
     */
    public String doGetQuotaCode() throws Exception {
        return iCQuota.createQuotaCode();
    }

    /**
     * 保存额度申请
     * 
     * @param quotaCode
     * @return
     * @throws Exception
     */
    public JResult doSaveQuotaApply(QuotaDto dto) throws Exception {
        JResult result = iCQuota.saveQuotaApply(dto);
        if (!result.isSuccess()) {
            return result;
        }

        // 将额度申请注册到接口协助服务中
        String quotaCode = dto.getQuotaCode();
        iInteractAssist.registerDealIrtService(quotaCode);
        /* 保存执行上下文 */
        interactClassInvokeService.saveInteractClassInvoke(quotaCode, this.getClass(), "doStartWork", quotaCode);
        return result;
    }

    /**
     * 开启额度申请(事务级别)
     */
    public JResult doStartWork(String quotaCode) throws Exception {
        return iCQuota.startWork(quotaCode);
    }

    /**
     * 创建额度申请
     * 
     * @param dto
     * @param quotaCode 额度申请编号
     * @return
     */
    public JResult quotaApply(QuotaDto dto) throws Exception {
        JResult result = new JResult();

        String quotaCode = doGetQuotaCode();
        // 保存额度申请
        dto.setQuotaCode(quotaCode);
        try {
            result = doSaveQuotaApply(dto);
            if (!result.isSuccess()) {
                return result;
            }

            doStartWork(quotaCode);
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new CimsException(quotaCode + ";" + e.getMessage());
        }
        // 开启额度申请
        result.setSuccess(true);
        return result;
    }

    public List<QuotaCreditDetailDto> searchQuotaCreditDetailByPaging(Map<String, Object> searchParams) {
        return dao.searchQuotaCreditDetailByPaging(searchParams);
    }

    /**
     * 释放额度申请
     * 
     * @param unlockDto
     * @return
     */
    public QuotaDetailUnlockResultDto doQuotaUnlock(QuotaDetailUnlockParamDto unlockDto) throws Exception {
        // TODO implement here
        this.iCInteract.quotaDetailUnlock(unlockDto);
        return null;
    }

    /**
     * 更新额度使用状态
     * 
     * @param quotaBatchId
     * @param quotaList
     * @return
     */
    public void doRefreshQuotaListStatus(String quotaBatchId, List<Map<String, Object>> quotaList) throws Exception {
        // TODO implement here

    }

    /**
     * 本地更新额度申请相关信息
     * 
     * @param quotaType
     * @param quotaCode
     * @param detailList 返回需要被释放的明细列表
     * @return void
     * @author chenguixue
     * @date 2015-1-30-下午4:54:49
     * @update
     */
    public void doDeleteQuotaLocal(String quotaType, String quotaCode, List<Object> detailList,
            StringBuffer busiInteractCode) throws Exception {
    	QuotaDto tcMmQuotaDTO = new QuotaDto();
    	tcMmQuotaDTO.setQuotaCode(quotaCode);
    	iCQuota.doSingleGetCreditRightQuotaApplyResult(tcMmQuotaDTO);
        iCQuota.deleteQuota(quotaCode, detailList);
        busiInteractCode.append(iInteractAssist.getBusiNoForInteract());
        iInteractAssist.registerDealIrtService(busiInteractCode.toString(), CimsConstant.INTERACT_NUM_TWO);
    }

    /**
     * 调用接口进行删除额度处理, 这个逻辑写的很垃圾，回头优化吧
     * 
     * @param quotaType
     * @param quotaCode
     * @param detailList
     * @return
     * @return String
     * @author chenguixue
     * @throws Exception 
     * @date 2015-1-30-下午4:55:38
     * @update
     */
    public void doDeleteQuotaInteract(String quotaType, String quotaCode, List<Object> detailList,
            String busiInteractCode) throws Exception {
        // 查询额度实体
        QuotaDto quotaDto = iCQuota.getQuotaByCode(quotaCode);
        if (CimsConstant.QUOTATYPE_LOAN.equals(quotaDto.getQuotaType())) {
            // 调用额度申请取消接口
            QuotaApplyParamDto quotaApplyParamDto = new QuotaApplyParamDto();
            quotaApplyParamDto.setDealCode(busiInteractCode);
            quotaApplyParamDto.setQuotaType(quotaDto.getQuotaType());
            quotaApplyParamDto.setQuotaDto(quotaDto);
            quotaApplyParamDto.setOperType(CimsIrtUrlConstant.IRT_QUOTAAPPLY_OPERTYPE_CANCEL); // 额度取消

            TCMmCooperorgDTO tcmmCooperorgDTO = new TCMmCooperorgDTO();
            tcmmCooperorgDTO.setCooperorgCode(quotaDto.getCooperorgCode());
            List<TCMmCooperorgDTO> cooperOrgList = tcmmCooperorgDao.searchTCMmCooperorg(SearchParamUtil
                    .getSearchParam(tcmmCooperorgDTO));
            if (cooperOrgList != null && cooperOrgList.size() > 0) {
                quotaDto.setCooperOrgName(cooperOrgList.get(0).getCooperorgName());
            }

            iCInteract.quotaCancel(quotaApplyParamDto);

            // 调用额度明细释放接口
            QuotaDetailUnlockParamDto quotaDetailUnlockParamDto = new QuotaDetailUnlockParamDto();
            quotaDetailUnlockParamDto.setDealCode(busiInteractCode);
            quotaDetailUnlockParamDto.setQuotaType(quotaDto.getQuotaType());
            List<QuotaDetailUnlockParamDto.LoanUnlockInfo> unlockList = new ArrayList<QuotaDetailUnlockParamDto.LoanUnlockInfo>();
            QuotaDetailUnlockParamDto.LoanUnlockInfo loanUnlockDto = null;

            if (detailList != null&&!detailList.isEmpty()) {
                for (Object obj : detailList) {
                    TCMmQuotaLoanDetailDTO loan = (TCMmQuotaLoanDetailDTO) obj;
                    loanUnlockDto = new QuotaDetailUnlockParamDto.LoanUnlockInfo();
                    unlockList.add(loanUnlockDto);
                    loanUnlockDto.setContractNo(loan.getContractNo());
                    loanUnlockDto.setUnlockType(CimsConstant.LOAN_OPER_TYPE_CC);
                    loanUnlockDto.setUnlockReason("");
                }
                quotaDetailUnlockParamDto.setUnlockList(unlockList);
               
                iCInteract.quotaDetailUnlock(quotaDetailUnlockParamDto);
            }
        }

        if (CimsConstant.QUOTATYPE_CR.equals(quotaDto.getQuotaType())) {
            QuotaApplyParamDto quotaApplyParamDto = new QuotaApplyParamDto();
            quotaApplyParamDto.setDealCode(busiInteractCode);
            quotaApplyParamDto.setQuotaType(quotaDto.getQuotaType());
            quotaApplyParamDto.setQuotaDto(quotaDto);
            iCInteract.quotaCancel(quotaApplyParamDto);

            // 调用额度明细释放接口
            QuotaDetailUnlockParamDto quotaDetailUnlockParamDto = new QuotaDetailUnlockParamDto();
            quotaDetailUnlockParamDto.setQuotaType(quotaDto.getQuotaType());
            quotaDetailUnlockParamDto.setDealCode(busiInteractCode);
            List<QuotaDetailUnlockParamDto.CreditRightUnlockInfo> unlockList = new ArrayList<QuotaDetailUnlockParamDto.CreditRightUnlockInfo>();
            QuotaDetailUnlockParamDto.CreditRightUnlockInfo creditUnlockDto = null;

            if (detailList != null&&!detailList.isEmpty()) {
                for (Object obj : detailList) {
                    TCMmQuotaCreditDetailDTO credit = (TCMmQuotaCreditDetailDTO) obj;
                    creditUnlockDto = new QuotaDetailUnlockParamDto.CreditRightUnlockInfo();
                    unlockList.add(creditUnlockDto);
                    creditUnlockDto.setCreditId(credit.getCreditCode());
                    creditUnlockDto.setTransferId(credit.getTransferId());
                    creditUnlockDto.setFreeValue(credit.getThisCreditorValue());
                    creditUnlockDto.setEachRepaymentValue(credit.getThisRepaySum());
                    creditUnlockDto.setIsWhole(CimsConstant.CREDIT_ISWHOLE);
                }
                quotaDetailUnlockParamDto.setCreditRightUnlockList(unlockList);
                quotaDetailUnlockParamDto.setSource(CimsConstant.QUOTA_UNLOCK_SOURCE);
                iCInteract.quotaDetailUnlock(quotaDetailUnlockParamDto);
            }
        }

    }

    /**
     * 删除额度 分开事务进行处理
     * 
     * @param dto .
     * @param quotaCode
     * @return void
     * @author chenguixue
     * @throws Exception 
     * @date 2015-1-30-上午10:49:56
     * @update
     */
    public void doQuotaDeleteById(BaseDTO dto, String quotaType, String quotaCode) throws Exception {
    	QuotaDto quotaDto = iCQuota.getQuotaByCode(quotaCode);
    	if(CimsConstant.QUOTA_STATUS_UNLOCK.equals(quotaDto.getQuotaStatus())){
    		throw new CimsException(MessageFormat.format("额度申请流水号[{0}]已释放，不可以删除！", new Object[] { quotaCode}));
    	}
    	
    	if (CimsConstant.QUOTATYPE_LOAN.equals(quotaDto.getQuotaType())) { 
		    deleteLoanQuota(quotaDto);
		}else{
			List<Object> detailList = new ArrayList<Object>();
	        StringBuffer busiInteractCode = new StringBuffer();
	        doDeleteQuotaLocal(quotaType, quotaCode, detailList, busiInteractCode); // 本地更新
	        
	        
	        Map<Object, Object> paramterMap = new HashMap<Object, Object>();
	        paramterMap.put("quotaType", quotaType);
	        paramterMap.put("quotaCode", quotaCode);
	        batchService.batchInvoke(QuotaService.class, "doBatchDeleteQuotaInteract", detailList, paramterMap, 500);
//	        doDeleteQuotaInteract(quotaType, quotaCode, detailList, busiInteractCode.toString()); // 调用接口
		}
    }
    
    /**
     * @throws Exception 
     * 删除额度释放债权提供批量处理
     * @Title doBatchDeleteQuotaInteract
     * @Description TODO
     * @param quotaType
     * @param quotaCode
     * @param detailList 
     * void 
     * @author lizhiqiang
     * @date 2016-5-18-下午7:11:11
     * @update 
     * @throws
     */
    public void doBatchDeleteQuotaInteract(List<Object> detailList ,Map<Object, Object> paramterMap ) throws Exception{
    	String quotaType = (String) paramterMap.get("quotaType");
    	String quotaCode = (String) paramterMap.get("quotaCode");
    	try {
    		doDeleteQuotaInteract(quotaType, quotaCode, detailList,iInteractAssist.getBusiNoForInteract()); // 调用接口
		} catch (Exception e) {
			e.printStackTrace();
			dobackQuotaDetailByQuotaForException(quotaCode,detailList);
		}
    	
    }

	/**
	 * 
	 * @Title cancelQuotaDetailByQuotaForException
	 * @Description TODO
	 * @param quotaCode
	 * @param detailList
	 * @return 
	 * List<Object> 
	 * @author lizhiqiang
	 * @date 2016-5-19-下午5:58:16
	 * @update 
	 * @throws
	 */
	public void dobackQuotaDetailByQuotaForException(String quotaCode, List<Object> detailList) {
		
		StringBuffer transferIds = new StringBuffer();
		for (Object object : detailList) {
			TCMmQuotaCreditDetailDTO credit = (TCMmQuotaCreditDetailDTO) object;
			transferIds.append(credit.getTransferId()).append("','");
		}
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, Object> dto = new HashMap<String, Object>();
		dto.put("quotaCode", quotaCode);
		dto.put("invalidStatus", CimsConstant.QUOTA_DETAIL_STATUS_INVALID);
		dto.put("newStatus", CimsConstant.QUOTA_DETAIL_STATUS_NEW);
		dto.put("transferIds", transferIds.substring(0, transferIds.length()-3).toString());
		searchParams.put("dto", dto);
		
		dao.dobackCancelQuotaCRDetailByQuota(searchParams);
		
		// 设置额度申请为有效状态， 释放为申请状态
		Map<String, Object> qsearchParams = new HashMap<String, Object>();
		QuotaDto quotaDto = new QuotaDto();
		quotaDto.setQuotaCode(quotaCode);
		quotaDto.setQuotaStatus(CimsConstant.QUOTA_STATUS_ST);
		quotaDto.setValidateState(CimsConstant.DATE_STATUS_VALID);
		qsearchParams.put("dto", quotaDto);
		dao.cancelQuota(qsearchParams);
	}
    /**
     * 分配额度明细给指定交易
     * 
     * @param detailCode
     * @param dealCode
     * @param value
     */
    public void allocToDeal(String detailCode, String dealCode, BigDecimal value) throws Exception {
        // TODO implement here
    }

    /**
     * @author JY-IT-D001
     * @description: 分页查询 t_c_mm_quota列表
     * @date 2015-01-14 10:07:19
     * @param searchParams 条件
     * @return
     * @throws
     */
    public List<QuotaDto> searchQuotaByPaging(Map<String, Object> searchParams) throws Exception {
        List<QuotaDto> dataList = dao.searchQuotaByPaging(searchParams);
        return dataList;
    }

    /**
     * @author JY-IT-D001
     * @description: 按条件查询t_c_mm_quota列表
     * @date 2015-01-14 10:07:19
     * @param searchParams 条件
     * @return
     * @throws
     */
    public List<QuotaDto> searchQuota(Map<String, Object> searchParams) throws Exception {
        List<QuotaDto> dataList = dao.searchQuota(searchParams);
        return dataList;
    }

    /**
     * 根据合作机构编号 合约编号查询 额度申请贷款明细
     * 
     * @author
     * @description:查询对象T_C_MM_QUOTA_LOAN_DETAIL
     * @date 2015-01-14 16:43:14
     * @param searchParams
     * @return
     */
    public List<TCMmQuotaLoanDetailDTO> getQuotaLoanDetailByPaging(Map<String, Object> searchParams) {
        return quotaLoanDetailDao.getQuotaLoanDetailByPaging(searchParams);
    }

    /**
     * 贷款转出流水号
     * 
     * @param quotaCode
     * @return
     */
    public JResult doGetDealCode(StringBuffer dealCode) throws Exception {
        JResult result = new JResult();
        dealCode = dealCode.append(iCDeal.createDealCode(CimsConstant.BIZNO_TYPE_LOAN));
        result.setSuccess(true);
        if (StringUtils.isBlank(dealCode)) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 获取数据不存在贷款信息表的记录
     * 
     * @param quotaCode 额度申请编号
     * @param LoanInfoList 筛选前没处理的贷款信息
     * @return 处理后的贷款信息，在数据库表已经存在的需要过滤掉
     */
    public List<LoanInfo> getNotExistLoanInfoList(String quotaCode, List<LoanInfo> loanInfoList) {
       
        return iCQuota.getNotExistLoanInfoList(quotaCode, loanInfoList);
    }

    /**
     * 系统自动根据额度结束日期刷新额度申请状态
     * 
     * @return void
     * @author chenguixue
     * @throws ParseException
     * @date 2015-1-29-下午1:50:50
     * @update
     */
    public void endQuota() throws ParseException {
        String datestr = DateTimeUtils.formatDate(new Date(), DateTimeUtils.DEFAULT_DATE_TIME_FORMAT);
        Date date = DateTimeUtils.parseDate(datestr, DateTimeUtils.DEFAULT_DATE_TIME_FORMAT);
        iCQuota.endQuota(date);
    }


    /**
     * @description 删除贷款额度申请信息
     * @param quotaDto 额度申请
     * @throws Exception
     */
    public void deleteLoanQuota(QuotaDto quotaDto) throws Exception {
		List<Object> detailList = new ArrayList<Object>();

		// 删除额度申请
		iCQuota.deleteQuota(quotaDto.getQuotaCode(), detailList);

		// 调用额度申请取消接口
		iCQuota.quotaCancel(quotaDto);

		// 调用额度明细释放接口
		iCQuota.quotaDetailUnlock(quotaDto, detailList);
	}
    
    /**
     * @description 删除贷款额度明细申请信息
     * @param quotaDto 额度申请
     * @throws Exception
     */
    public void deleteLoanQuotaDetail(QuotaDto quotaDto,String contractNo) throws Exception {
		List<Object> detailList = new ArrayList<Object>();
		Date date = new Date();
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	String riskTimeString = format.format(date);
		// 删除额度申请明细
		iCQuota.cancelQuotaDetailByQuotaDetail(contractNo,detailList,riskTimeString);

		// 调用额度明细释放接口
		iCQuota.quotaDetailUnlock(quotaDto, detailList);
	}
    
    /**
     * @description 新增贷款申请信息
     * @param quotaDto 额度申请
     * @throws Exception
     */
    public void addLoantQuotaApply(QuotaDto quotaDto) throws Exception {
    	
    	// 新增贷款申请信息
        iCQuota.addLoantQuotaApply(quotaDto);
    }
    
    /**
     * 审核额度申请（贷款）
     * 
     * @param dto
     * @param quotaCode 额度申请编号
     * @return
     */
    public void updateQuotaApply(String quotaCode) throws Exception {
        
        
        try {
        	JResult result = new JResult();
        	// 调合同调配-额度申请
            result = doStartWork(quotaCode);
            if (!result.isSuccess()) {
            	throw  new  Exception();
            }
        }catch (Exception e) {
            throw new CimsException(">>>>结算申请编号【"+quotaCode+"】额度申请调合同调配失败,失败原因：>>>>>"+ e.getMessage());
        }
        
        try {
            // 本地额度申请表-申请状态更新 由待审核 更新为 申请中
            doUpdateQuotaApply(quotaCode);
            
        }catch (Exception e) {
        	 throw new CimsException(">>>>结算申请编号【"+quotaCode+"】更新额度申请状态失败,失败原因：>>>>>"+ e.getMessage());
        }  
    }
    
    /**
     * 额度申请审核-更新额度申请状态 （贷款）
     * 
     * @param quotaCode
     * @return
     * @throws Exception
     */
    public void doUpdateQuotaApply(String quotaCode) throws Exception {
    	iCQuota.updateQuotaStatusByQuotaCode(quotaCode);
    }
    
    /**
	 * 
	 * 
	 * @return void
	 * @author chenguixue
	 * @date 2015-1-27-下午5:38:05
	 * @update
	 */
	public void doWork(final QuotaDto quotaDto) throws Exception {
		if (null == quotaDto) {
			return;
		}

		logger.info("额度申请编号:" + quotaDto.getQuotaCode());
		String dealCode = iInteractAssist.getBusiNoForInteract();
		
		QuotaApplyParamDto paramDto = new QuotaApplyParamDto();
		paramDto.setPageSize(CimsConstant.DEFAULT_PAGE_SIZE);
		paramDto.setCurPage(1);
		paramDto.setQuotaDto(quotaDto);
		paramDto.setQuotaType(CimsConstant.QUOTATYPE_LOAN);
		paramDto.setDealCode(dealCode);

		// 获取数据
		logger.info("异步获取额度申请结果 贷款和债权start");
		QuotaApplyResultDto resultDto = iCInteract.getQuotaApplyResult(paramDto);
		logger.info("异步获取额度申请结果 贷款和债权end");
		if (resultDto == null) {
			return;
		}

		// 计算分页
		int totalCount = resultDto.getTotalRows();
		int pageSum = totalCount / CimsConstant.DEFAULT_PAGE_SIZE;

		if (totalCount <= 0) {
			return;
		}

		pageSum = (totalCount % CimsConstant.DEFAULT_PAGE_SIZE == 0) ? pageSum : pageSum + 1;

		// 保存当页数据
		List<LoanInfo> loanInfoList = getNotExistLoanInfoList(quotaDto.getQuotaCode(), resultDto.getLoanList());
		iCQuota.saveLoanFromInteract(loanInfoList, null);
		// 重复执行后续页
		for (int curPage = 2; curPage < pageSum + 1; curPage++) {
			paramDto.setCurPage(curPage);
			resultDto = iCInteract.getQuotaApplyResult(paramDto);
			loanInfoList = getNotExistLoanInfoList(quotaDto.getQuotaCode(), resultDto.getLoanList());
			iCQuota.saveLoanFromInteract(loanInfoList, null);
		}

		paramDto = null;
	}
	
	/**
	 * 债权额度撤销
	 * @author zhangmi
	 * @date  2017年3月8日
	 * @param quotaType
	 * @param quotaCode
	 */
	public boolean doQuotaCreditBack(String quotaCode) throws Exception{
		QuotaDto quotaDto = iCQuota.getQuotaByCode(quotaCode);
		if(CimsConstant.QUOTATYPE_CR.equals(quotaDto.getQuotaType())){
			 
			boolean dealStatusFlag_new = false;
			boolean dealStatusFlag_lock = false;
			boolean dealStatusFlag_invalid = false;
			TCMmQuotaCreditDetailDTO searchDto = new TCMmQuotaCreditDetailDTO();
			searchDto.setQuotaCode(quotaDto.getQuotaCode());
//			searchDto.setQuotaType(quotaDto.getQuotaType());
			List<TCMmQuotaCreditDetailDTO> list = iCQuota.searchTCMmQuotaCreditDetail(SearchParamUtil.getSearchParam(searchDto));
			QuotaApplyParamDto paramDto = new QuotaApplyParamDto();
			paramDto.setQuotaDto(quotaDto);
			paramDto.setDealCode(quotaDto.getQuotaCode());
			paramDto.setBackType(CimsConstant.QUOTABACK_02);
			if(CollectionsUtils.isNotEmpty(list)){
				 //
				for (TCMmQuotaCreditDetailDTO quotaCreditDetailDto : list) {
					if(CimsConstant.QUOTA_DETAIL_STATUS_NEW.equals(quotaCreditDetailDto.getDealStatus())){
							dealStatusFlag_new = true;
					}
					if(CimsConstant.QUOTA_DETAIL_STATUS_LOCK.equals(quotaCreditDetailDto.getDealStatus())){
							dealStatusFlag_lock = true;
					}
					if(CimsConstant.QUOTA_DETAIL_STATUS_INVALID.equals(quotaCreditDetailDto.getDealStatus())){
							dealStatusFlag_invalid = true;
					}
				}
				//全部是申请状态
				if(dealStatusFlag_new
						&&!dealStatusFlag_lock
						&&!dealStatusFlag_invalid){
					//直接删除
					//调用接口
					QuotaApplyResultDto result = creditPoolIFImpl.quotaCancel(paramDto);
					if(result!=null){
						iCQuota.updateCncelQuotaCRDetailByQuota(quotaCode, CimsConstant.QUOTA_DETAIL_STATUS_NEW);
						iCQuota.updateCancelQuotaStatusByQuotaCode(quotaCode, CimsConstant.QUOTA_STATUS_UNLOCK);
						return true;
					}else{
						logger.error("申请：额度释放接口调用失败！");
					}
				}
				//全部是作废
				else if(dealStatusFlag_invalid
						&&!dealStatusFlag_new
						&&!dealStatusFlag_lock){
					//调用接口
					creditPoolIFImpl.quotaCancel(paramDto);
					iCQuota.updateCancelQuotaStatusByQuotaCode(quotaCode, CimsConstant.QUOTA_STATUS_UNLOCK);
					return true;
				//申请-作废
				}else if(dealStatusFlag_invalid
						&&dealStatusFlag_new
						&&!dealStatusFlag_lock){
					QuotaApplyResultDto result = creditPoolIFImpl.quotaCancel(paramDto);
					if(result!=null){
						iCQuota.updateCncelQuotaCRDetailByQuota(quotaCode, CimsConstant.QUOTA_DETAIL_STATUS_NEW);
						iCQuota.updateCancelQuotaStatusByQuotaCode(quotaCode, CimsConstant.QUOTA_STATUS_UNLOCK);
						return true;
					}else{
						logger.error("申请-作废：额度释放接口调用失败！");
					}
				} else{
					logger.error("该额度不能直接释放！"+quotaCode);
				}
			}else{
				//直接释放
				creditPoolIFImpl.quotaCancel(paramDto);
				iCQuota.updateCancelQuotaStatusByQuotaCode(quotaCode, CimsConstant.QUOTA_STATUS_UNLOCK);
				return true;
			}
			 
		}else{
			logger.info("只处理债权额度！贷款额度暂不处理！");
		}
		return false;
	}
}
